<template>
  <div class="main_box" style="padding:10px">
    <div class="add_wrap">
      <div class="tit">
        <h2>
          {{ dataForm.tagId ? "编辑按键样式模板" : "新增按键样式模板" }}
        </h2>
        <el-button
          type="success"
          plain
          size="small"
          icon="fa fa-mail-forward"
          @click="returnList"
          >返回</el-button
        >
      </div>
      <el-form
        :model="dataForm"
        ref="dataForm"
        label-width="200px"
        :rules="roleRules"
      >
        <el-row>
            <el-form-item label="模板名称" prop="modelName">
                <el-input v-model="dataForm.modelName"></el-input>
            </el-form-item>
        </el-row>
        <el-row >
          <el-row
            type="flex"
            style="align-items:center;margin-left: 4px;justify-content: space-between;"
          >
            <h2>模板数据</h2>
            <el-button
              type="success"
              plain
              circle
              icon="el-icon-plus"
              @click="dataForm.btnModelRelations.push($options.data().dataForm.btnModelRelations[0])"
            ></el-button>
          </el-row>
          <el-row style="width:fit-content">


          <el-table :data="dataForm.btnModelRelations" :key="tableKey">
            <el-table-column label="删除" align="center" width="80">
              <template slot-scope="{ row, $index }">
                <el-button
                  type="danger"
                  plain
                  circle
                  icon="el-icon-minus"
                  @click="dataForm.btnModelRelations.splice($index, 1)"
                ></el-button>
              </template>
            </el-table-column>
            <el-table-column label="模块类型" align="center" width="130">
              <template slot-scope="{ row, $index }">
                <el-select
                  v-model="row.moduleType"
                  placeholder="请选择模块类型"
                  clearable
                  filterable
                  @change="handleModuleTypeChange($index)"
                >
                  <el-option
                    v-for="item in $Options.moduleTypeList"
                    :value="item.id"
                    :label="item.name"
                    :key="item.id"
                  ></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="标识图" align="center" width="120">
              <template slot-scope="scope">
                <div style="width: 100px;height:100px;">
                  <UploadImg
                    class="upload-img"
                    v-if="!scope.row.tagUrl"
                    @uploadFileList="getFileUrl"
                    :index="scope.$index"
                    :param="{prop:'tagUrl'}"
                    folder="common"
                  />
                  <div class="image_container" v-else @mouseenter="imgMaskIndexShow = scope.$index">
                    <div class="mask" v-show="imgMaskIndexShow === scope.$index" @mouseleave="imgMaskIndexShow = undefined">
                      <i class="el-icon-zoom-in" style="color: white" @click="handlePicturesPreview(scope.row.tagUrl)" />
                      <i class="el-icon-delete" style="color: white" @click="handlePicturesDelete('tagUrl', scope.$index)" />
                    </div>
                    <el-image
                        style="width: 100px; height:100px"
                        fit="cover"
                        :src="scope.row.tagUrl"
                        :preview-src-list="[scope.row.tagUrl]"
                    ></el-image>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="标识图底部边距" align="center" width="120">
              <template slot-scope="{row}">
                <el-input v-model="row.bottomMargin" type="number"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="排序" align="center">
              <template slot-scope="scope">
                <el-input type="number" v-model.number="scope.row.sort"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="banner高度" align="center" width="120">
              <template slot-scope="{ row }">
                <el-input
                  v-if="row.moduleType == 2"
                  type="number"
                  v-model="row.bannerHeight"
                ></el-input>
                <span v-else>#</span>
              </template>
            </el-table-column>
            <el-table-column label="大图" align="center" width="120">
              <template slot-scope="scope">
                <div style="width: 100px;height:100px;" v-if="scope.row.moduleType==5">
                  <UploadImg
                    class="upload-img"
                    v-if="!scope.row.bigImgUrl"
                    @uploadFileList="getFileUrl"
                    :param="{prop:'bigImgUrl'}"
                    :index="scope.$index"
                    folder="common"
                  />
                  <div class="image_container" v-if="scope.row.bigImgUrl" @mouseenter="bigImgMaskIndexShow = scope.$index">
                    <div class="mask" v-show="bigImgMaskIndexShow === scope.$index" @mouseleave="bigImgMaskIndexShow = undefined">
                      <i class="el-icon-zoom-in" style="color: white" @click="handlePicturesPreview(scope.row.bigImgUrl)" />
                      <i class="el-icon-delete" style="color: white" @click="handlePicturesDelete('bigImgUrl',scope.$index)" />
                    </div>
                    <el-image style="width: 100px; height:100px" fit="cover" :src="scope.row.bigImgUrl"/>
                  </div>
                </div>
                <span v-else />
              </template>
            </el-table-column>
            <el-table-column label="列表标题" align="center" width="160">
              <template slot-scope="{ row }">
                <el-input
                  v-if="row.moduleType == 4"
                  v-model="row.listTitle"
                ></el-input>
                <span v-else>#</span>
              </template>
            </el-table-column>
            <el-table-column label="列表布局" align="center" width="130">
              <template slot-scope="{row}">
                <el-select v-model="row.styleType" v-if="row.moduleType==4">
                  <el-option :value="1" label="一行一列"></el-option>
                  <el-option :value="2" label="一行两列"></el-option>
                </el-select>
                <span v-else>#</span>
              </template>
            </el-table-column>
            <el-table-column label="行列" align="center" width="90">
              <template slot-scope="{ row,$index }">
                <div>
                  <el-button
                    v-if="row.moduleType == 1"
                    size="mini"
                    @click="handleRowCol(row,$index)"
                    >编辑</el-button
                  >
                  <span v-else="row.moduleType != 1">#</span>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        </el-row>

        <el-row>
          <el-form-item>
            <el-button plain type="primary" @click="sureClick">保 存</el-button>
            <el-button plain @click="returnList">取 消</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>

    <el-dialog :visible.sync="rowCol.show" center title="添加行列" width="fit-content">
      <div style="text-align: end;margin-bottom: 10px;">
        <el-button
          type="success"
          plain
          circle
          icon="el-icon-plus"
          @click="rowCol.list.push($options.data().rowCol.list[0])"
        ></el-button>
      </div>
      <el-table :data="rowCol.list">
        <el-table-column label="删除" align="center" width="120">
          <template slot-scope="{ row, $index }">
            <el-button
              type="danger"
              plain
              circle
              icon="el-icon-minus"
              @click="row.list.splice($index, 1)"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column label="行数" align="center" width="150">
          <template slot-scope="{ row }">
            <el-input type="number" v-model="row.row"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="列数" align="center" width="150">
          <template slot-scope="{ row }">
            <el-input type="number" v-model="row.col"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" width="150">
          <template slot-scope="{ row }">
            <el-input type="number" v-model.number="row.sort"></el-input>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer">
        <el-button type="primary" @click="confirmRowCol">确定</el-button>
        <el-button @click="rowCol.show = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as message from "@/constants/message";
import UploadImg from "@/components/UploadImg";
import BtnModelApi from "@/api/server/btnModel";
import { nanoid } from "nanoid";
export default {
  name: "BtnModelAdd",
  data() {
    return {
      tableKey:nanoid(),
      dataForm: {
        modelId:"",
        modelName:"",
        btnModelRelations: [
          {
            moduleType: "",
            tagUrl: "",
            bottomMargin:"",
            sort: "",
            listTitle:"",
            bigImgUrl:"",
            bannerHeight:"",
            styleType:1,
            btnFormats: []
          }
        ]
      },
      roleRules: {
        modelName:[
            {required: true, message: '请输入模块名称', trigger: 'blur'}
        ]
      },
      rowCol: {
        list: [
            {row:"",col:"",sort:""}
        ],
        show: false,
        index: ""
      },
      imgMaskIndexShow: undefined,  // 标识图遮罩是否显示
      bigImgMaskIndexShow: undefined // 大图遮罩是否显示
    };
  },
  components: {
    UploadImg
  },
  mounted() {
    const {id} = this.$route.query
    if(id){
      this.dataForm.modelId = id;
      this.getData()
    }
  },
  methods: {
    keydown(e) {
      if (e.keyCode == 32) {
        e.returnValue = false;
      }
    },
    async getData() {
      const {data} = await BtnModelApi.getBtnModel({id:this.dataForm.modelId});
      this.$Utils.bindingBean(this.dataForm,data);
    },
    // 模块类型改变
    handleModuleTypeChange(index) {
      const { moduleType } = this.dataForm.btnModelRelations[index];
      this.$set(this.dataForm.btnModelRelations, index, {
        ...this.$options.data().dataForm.btnModelRelations[0],
        moduleType
      })
    },
    getFileUrl(val) {
      if (val) {
        this.$Utils.notifySuccess("上传成功");
      }
      console.log(val,"上传成功")
      this.dataForm.btnModelRelations[val.index][val.param['prop']] = val.uploadFileList[0];
      console.log(this.dataForm.btnModelRelations)
    },
    handleRowCol(row, index) {
      const { rowCol } = this;
      rowCol.index = index;
      this.$set(rowCol, "list",JSON.parse(JSON.stringify(row.btnFormats)));
      rowCol.show = true;
    },
    confirmRowCol(){
        const {rowCol,dataForm} = this
        dataForm.btnModelRelations[rowCol.index].btnFormats = rowCol.list
        rowCol.show = false
    },
    checkData(){
      let {btnModelRelations} = this.dataForm
      this.dataForm.btnModelRelations = btnModelRelations = btnModelRelations.filter(item=>item.moduleType)
      for(let i=0;i<btnModelRelations.length;i++){
        let item = btnModelRelations[i]
        if(!item.sort){
          this.$message.error(`请输入第${i+1}行排序`)
          return
        }
        switch(item.moduleType){
          case 1:
            if(!item.btnFormats.length){
              this.$message.error(`请编辑第${i+1}行添加行和列`)
               return
            }else{
              if(item.btnFormats.some(item=>!item.sort||!item.row||!item.col)){
                this.$message.error(`请编辑第${i+1}行信息添加完整`)
                return
              }
            }

            break
          case 4:
            if(!item.listTitle){
              this.$message.error(`请输入第${i+1}行的列表标题`)
               return
            }
            break
          case 5:
            if(!item.bigImgUrl){
              this.$message.error(`请输入第${i+1}行的banner大图`)
               return
            }

        }
      }

      return true
    },
    sureClick() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          if(!this.checkData()) return
          this.$confirm(
            message.MSG_CONFIRM_SAVE_ALTER,
            message.TITLE_PROMPT,
            {}
          ).then(() => {
            if (this.dataForm.modelId) {
              this.editData();
            } else {
              this.addData();
            }
          });
        }
      });
    },
    addData() {
     const params = {...this.dataForm}
     Reflect.deleteProperty(params,'modelId')
      BtnModelApi.addBtnModel(params).then(res => {
        this.$Utils.notifySuccess();
        this.returnList();
      });
    },
    editData() {
      BtnModelApi.editBtnModel(this.dataForm).then(() => {
        this.$Utils.notifySuccess();
        this.returnList();
      });
    },
    returnList() {
      this.$store.dispatch("delView", this.$route);
      this.$router.push({
        path: "/server/btnModelManagement"
      });
    },

    /**
     * 图片预览
     * @param url
     */
    handlePicturesPreview(url) {
      window.open(url,'_blank')
    },

    /**
     * 图片删除
     * @param paramsKey
     * @param tableIndex
     */
    handlePicturesDelete(paramsKey, tableIndex) {
      this.dataForm.btnModelRelations[tableIndex][paramsKey] = ""
    }
  }
};
</script>
<style lang="scss" scoped>
@import "@/assets/css/views/add.scss";
</style>
<style lang="scss" scoped>
.upload-img {
  height: 100%;
  &::v-deep {
    .upload-oss {
      height: 100%;
      .el-upload {
        height: 100%;
        .el-upload-dragger {
          height: 100%;
        }
      }
    }
  }
  // .el-upload-dragger{

  // }
}
.image_container {
  position: relative;
  .mask {
    position: absolute;
    z-index: 2;
    width: 100px;
    height: 100px;
    background: rgba(0,0,0,0.4);
    display: flex;
    justify-content: center;
    align-items: center;
    color: white;
    font-size: 20px;
    i:first-child {
      margin-right: 10px;
    }
    i:hover {
      cursor: pointer;
    }
  }
}
</style>
